import React, {useContext, useState} from 'react';
import { Modal, StyleSheet, Alert, View, PermissionsAndroid } from 'react-native';
import { Text } from 'react-native-elements';

import { getVersion} from "./../libs/nodes";
import RNFetchBlob from 'rn-fetch-blob'
const pkg = require('../package.json');

import {ProgressBar} from '@react-native-community/progress-bar-android';
import WalletContext from "../libs/wallet";

const UpdateDialog = () => {
  const [storagePermission, setStoragePermission] = useState(false);

  const [modalVisible, setModalVisible] = useState(false);
  const [progressNumber, setProgressNumber] = useState(0);
  const wallet: any = useContext(WalletContext);

  //获取Android 读写SD权限;
  const requestPermissionFunction = async() =>
  {
    try {
      const permissions = [
        PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
      ];
      const granteds = await PermissionsAndroid.requestMultiple(permissions);
      if (granteds['android.permission.WRITE_EXTERNAL_STORAGE'] === 'granted') {
        setStoragePermission(true);
      } else {
        setStoragePermission(false);
        Alert.alert("请先开启权限！");
      }
      return storagePermission;
    } catch (err) {
      console.log(err);
    }
  }

  //TODO 更新下载
 const downloadAPKForInstall = async() => {
    if(storagePermission)
    {
      marchAndDownloadingForInstall();
    }else{
      requestPermissionFunction();
    }
  };

  //TODO 匹配本地appversion 并且 下载安装
  const marchAndDownloadingForInstall = async() => {
      const newVersion = await getVersion(pkg.version,wallet.address);
    console.log("checkAppVersion ===>>>>   " + JSON.stringify(newVersion));
      // if(!isNaN(newVersion.dict.version)){
        console.log("newVersion.dict.version ===>>>>   " + newVersion.dict.version + ' pkg.version: '+pkg.version);
        if(checkAppVersion(newVersion.dict.version, pkg.version)){
          Alert.alert('更新提示框', '检测到新版本,是否立即更新?',[{
            text: "取消",
            onPress: () => console.log("Cancel Pressed"),
            style: "cancel"
          },{text:'确定',onPress:()=>{
            setModalVisible(true);
            downloadAPKFile(newVersion.dict.url);
          }}]);
        }
      // }
  }

  //下载APK文件;
  const downloadAPKFile = async (dictUrl:any) =>
  {
    const downloadAndroid = await RNFetchBlob.android
    RNFetchBlob.config(
    {
      fileCache : true,
      path: `${RNFetchBlob.fs.dirs.DownloadDir}/update.apk`,
      //   addAndroidDownloads : {
      //   useDownloadManager : true,
      //   title : 'awesome.apk',
      //   description : 'An APK that will be installed',
      //   mime : 'application/vnd.android.package-archive',
      //   path: `${RNFetchBlob.fs.dirs.DownloadDir}/update.apk`,
      //   mediaScannable : true,
      //   notification : true,
      // }
    })
    .fetch('GET', dictUrl, {
        //... some headers,
        // 'Content-Type' : 'octet-stream'
    }).progress({count:100},(received,total) => {
      setProgressNumber((Math.round((received / total) * 100)));
    })
    // .then((res) => {
    //   downloadAndroid.actionViewIntent(res.path(), 'application/vnd.android.package-archive'), RNFetchBlob.fs.scanFile([{path:res.path(),mime:'apk'}])
    // })
    .then((res) => {
      setModalVisible(false);
      downloadAndroid.actionViewIntent(res.path(), 'application/vnd.android.package-archive')
    })
    .catch((err)=>{
      setModalVisible(false);
      console.log('downloadAPKForInstall err: ' + err);
    });
  }

  //检查是否有新的版本;
  const checkAppVersion = (serverVersionCode:any,localVersionCode:any) => {
    try{
      const currentVersionCode = formatVersionCode(localVersionCode);
      const newsVersionCode = formatVersionCode(serverVersionCode);
      console.log('checkAppVersion  localVersionCode: ' + currentVersionCode + ' newsVersionCode: ' + newsVersionCode);
      if(parseInt(currentVersionCode) < parseInt(newsVersionCode)){
        return true;
      }
    }catch(error){
      console.log(error);
    }
    return false;
  }

  //TODO  格式化VersionCode
  const formatVersionCode = (versionCode:any)=>{
    return versionCode.replace('.','').replace('.','');
  }

  return (
     <View>
      <Modal
            animationType='fade'
            statusBarTranslucent={true}
            transparent={true}
            visible={modalVisible}
            onRequestClose={()=>{
              setModalVisible(!modalVisible);
              // Alert.alert("Modal has been closed.");
            }}>
            <View style={styles.progressBarView}>
                <View style={styles.subView}>
                    <Text style={styles.title}>
                        {"正在下载,请稍后..."}
                    </Text>
                    <ProgressBar
                      color="black"
                      styleAttr="Horizontal"
                      indeterminate={false}
                      progress={
                        progressNumber / 100
                        } />
                    <View style = { styles.progressContainer }>
                        <Text style = { styles.progressLeftText }>
                            {
                              progressNumber
                            }%
                        </Text>
                        <Text style={styles.progressRightText}>
                          {
                              100
                          }%
                        </Text>
                    </View>
                </View>
            </View>
        </Modal>
     </View>
  );
};

const styles = StyleSheet.create({
  progressBarView: {
      flex:1,
      justifyContent: 'center',
      alignItems: 'center',
      backgroundColor: 'rgba(0,0,0,0.2)',
  },
  progressLeftText: {
      fontSize: 14
  },
  cancleContainer: {
      justifyContent: 'center',
      alignItems: 'flex-end'
  },
  progressRightText: {
      fontSize: 14,
      color: '#666666'
  },
  barBackgroundStyle: {
      backgroundColor: '#cccccc'
  },
  progressContainer: {
      flexDirection: 'row',
      padding: 10,
      justifyContent: 'space-between'
  },
  subView: {
      marginLeft: 30,
      marginRight: 30,
      paddingLeft:10,
      paddingRight:10,
      backgroundColor: '#fff',
      alignSelf: 'stretch',
      justifyContent: 'center',
      borderRadius:20,
  },
  progressView: {
      flexDirection: 'row',
      padding: 10,
      paddingBottom: 5,
      justifyContent: 'space-between'
  },
  title: {
      textAlign: 'left',
      padding:10,
      fontSize: 16
  },
  cancleButton: {
      padding:10
  },
  cancleText: {
      textAlign: 'right',
      paddingTop: 0,
      fontSize: 16,
      color: 'rgba(0, 122, 255, 1)'
  },
});

export default UpdateDialog;
